package server.com.acme.bankapp.domain.bank;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import server.com.acme.bankapp.service.bank.BankDataLoaderService;
import server.com.acme.bankapp.service.bank.BankService;

public class BankServer {
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	String[] data;
	BankService bankService;

	private final static String serv = "server>";
	private final static String client = "client>";
	private final static String bye = "bye";
	private final static String format = "Data received in unknown format";
	private final static String added = "Client was successfully added";
	private final static String space = " ";
	private final static String add = "add";
	private final static String wrong = "Wrong command";
	private final static String waiting = "Waiting for connection";
	private final static String conn = "Connection received from ";
	private final static String connSuccess = "Connection successful";
	private final static String hiServ = "Hi my server";
	private final static String hi = "Hi";

	public BankServer(BankService bankService) {
		this.bankService = bankService;
	}

	void parseQuery(String query) {
		data = query.split(space);
		if (data[0].equals(add)) {
			BankDataLoaderService loader = new BankDataLoaderService();
			loader.read(data[1], bankService);
			sendMessage(added);
		} else {
			sendMessage(wrong);
		}
	}

	void run() {
		try {
			providerSocket = new ServerSocket(2004, 10);
			System.out.println(waiting);
			connection = providerSocket.accept();
			System.out
					.println(conn + connection.getInetAddress().getHostName());
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage(connSuccess);
			do {
				try {
					message = (String) in.readObject();
					System.out.println(client + message);
					if (message.equals(bye)) {
						sendMessage(bye);
					} else if (message.equals(hiServ)) {
						sendMessage(hi);
					} else {
						parseQuery((String) message);
					}
				} catch (ClassNotFoundException classnot) {
					System.err.println(format);
				}
			} while (!message.equals(bye));
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				providerSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println(serv + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public void startServer(Bank bank) {
		while (true) {
			run();
		}
	}

}
